<template>
  <main class="site-content" :class="{ 'site-content--tabs': $route.meta.isTab }" v-loading.fullscreen.lock='loading'>
    <!-- 主入口标签页 s -->
    <keep-alive>
    <el-tabs
      v-if="$route.meta.isTab"
      v-model="mainTabsActiveName"
      :closable="true"
      @tab-click="selectedTabHandle"
      @tab-remove="removeTabHandle"
      >
      <el-dropdown class="site-tabs__tools" :show-timeout="0">
        <i class="el-icon-arrow-down el-icon--right"></i>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item @click.native="tabsCloseCurrentHandle">关闭当前标签页</el-dropdown-item>
          <el-dropdown-item @click.native="tabsCloseOtherHandle">关闭其它标签页</el-dropdown-item>
          <el-dropdown-item @click.native="tabsCloseAllHandle">关闭全部标签页</el-dropdown-item>
          <el-dropdown-item @click.native="tabsRefreshCurrentHandle">刷新当前标签页</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-tab-pane
        v-for="item in mainTabs"
        :key="item.name"
        :label="item.title"
        :name="item.name">
        <el-card :body-style="siteContentViewHeight">
          <iframe
            v-if="item.type === 'iframe'"
            :src="item.iframeUrl"
            width="100%" height="100%" frameborder="0" scrolling="yes">
          </iframe>
          <keep-alive v-else>
            <router-view v-if="item.name === mainTabsActiveName" />
          </keep-alive>
        </el-card>
      </el-tab-pane>
    </el-tabs>
    <!-- 主入口标签页 e -->
    <el-card v-else :body-style="siteContentViewHeight">
      <!-- <span @click="drawer=true">测试位置</span> -->
      <keep-alive>
        <router-view />
      </keep-alive>
    </el-card>
    </keep-alive>
    <el-drawer
      :visible.sync="drawer"
      direction="rtl"
      :close-on-press-escape='true'
      size=300
      :modal='false'
      :withHeader='false'>
      <div class="container">
        <el-collapse>
          <el-collapse-item v-for="(shop,index) in shopList" :key="index" disabled class="shopItem">
            <div class="el-collapse-item-title" slot="title" @click="switchUser(shop.loginName)">
              <img src="../../static/img/head.png" alt="" style="height:40px;margin:0;padding:0;" >
              <div class="shopInfo">
                <div>{{shop.shopName}}</div>
                <div class="createTime">开店时间：{{shop.createTime.split(' ')[0]}}</div>
              </div>
            </div>
            <div>
              地址：{{shop.province+shop.city+shop.area+shop.shopAddress}}
            </div>
          </el-collapse-item>
          <el-collapse-item class="menuItem" title="营业时间">
            <div style="padding-left:15px;">开店时间：<span style='font-size:30px;color:#D31414;'>{{openTime.split('-')[0]}}</span></div>
            <div style="padding-left:15px;">打烊时间：<span style='font-size:30px;color:#D31414;'>{{openTime.split('-')[1]}}</span></div>
            <!-- <div>{{shopStatus}}</div> -->
            <div style="padding-left:15px;">
              <el-button type="primary" size="small" @click="changeOpenTimeVisible = !changeOpenTimeVisible">更改营业时间</el-button>
            </div>
          </el-collapse-item>
          <el-collapse-item class="menuItem" title="修改密码" disabled @click.native="updatePasswordHandle()"></el-collapse-item>
          <el-collapse-item class="menuItem" title="返回首页" disabled @click.native="$router.push({ name: 'home' })"></el-collapse-item>
          <el-collapse-item class="menuItem" title="退出登录" disabled @click.native="logoutHandle()"></el-collapse-item>
        </el-collapse>
      </div>

    </el-drawer>

      <!-- 弹窗, 修改密码 -->
    <update-password v-if="updatePassowrdVisible" ref="updatePassowrd"></update-password>

    <el-dialog
      title="更改营业时间"
      :visible.sync="changeOpenTimeVisible"
      width="600px"
      center
      class="businessTime">
      <div style="margin: 0 auto;">
        <el-time-picker
          is-range
          v-model="businessTime"
          range-separator="至"
          start-placeholder="开店时间"
          end-placeholder="打烊时间"
          placeholder="选择时间范围">
        </el-time-picker>
        <!-- {{businessTime}}    -->
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changeOpenTimeVisible = false">取 消</el-button>
        <el-button type="primary" @click="changeOpenTime">确 定</el-button>
      </span>
    </el-dialog>

  </main>
</template>

<script>
  import { isURL } from '@/utils/validate'
  import UpdatePassword from './main-navbar-update-password'
  import { clearLoginInfo } from '@/utils'

  export default {
    data () {
      return {
        changeOpenTimeVisible: false,
        drawer: false,
        showBusinessTime: false,
        updatePassowrdVisible: false,
        businessTime: [],
        status: NaN,
        shopList: [],
        loading: false,
      }
    },
    components: {
      UpdatePassword
    },

    computed: {
      documentClientHeight: {
        get () { return this.$store.state.common.documentClientHeight }
      },
      menuActiveName: {
        get () { return this.$store.state.common.menuActiveName },
        set (val) { this.$store.commit('common/updateMenuActiveName', val) }
      },
      mainTabs: {
        get () { return this.$store.state.common.mainTabs },
        set (val) { this.$store.commit('common/updateMainTabs', val) }
      },
      mainTabsActiveName: {
        get () { return this.$store.state.common.mainTabsActiveName },
        set (val) { this.$store.commit('common/updateMainTabsActiveName', val) }
      },
      siteContentViewHeight () {
        var height = this.documentClientHeight - 50 - 30 - 2
        if (this.$route.meta.isTab) {
          height -= 40
          return isURL(this.$route.meta.iframeUrl) ? { height: height + 'px' } : { minHeight: height + 'px' }
        }
        return { minHeight: height + 'px' }
      },
      shopStatus:{
        get() {
          this.status = this.$store.state.user.shopStatus
          return this.$store.state.user.shopStatus
        },
        set(val){ this.$store.commit('user/updateShopStatus',val) }
      },
      shopId:{
        get (){ return this.$store.state.user.shopId },
      },
      openTime:{
        get (){
          var timeRange = this.$store.state.user.openTime
          var startRange = timeRange.split('-')[0]
          var endRange = timeRange.split('-')[1]
          var startTime = new Date(2020,8,14,startRange.split(':')[0],startRange.split(':')[1])
          var endTime = new Date(2020,8,14,endRange.split(':')[0],endRange.split(':')[1])
          this.businessTime= [startTime,endTime]
          return this.$store.state.user.openTime
        },
        set (val){
          console.log('settime running');
          this.$store.commit('user/shopOpenTime',val)
        }
      },
    },

    created(){
      this.getShops()
    },
    methods: {
      getShops(){
        this.$http({
          url: this.$http.adornUrl('/shop/shopDetail/getAllShopDetailByOnePerson'),
          method: 'get',
        }).then(({data}) =>{
          this.shopList = data
        })
      },

      openSideBar () {
        this.drawer = true
      },

      // tabs, 选中tab
      selectedTabHandle (tab) {
        tab = this.mainTabs.filter(item => item.name === tab.name)
        if (tab.length >= 1) {
          this.$router.push({ name: tab[0].name })
        }
      },
      // tabs, 删除tab
      removeTabHandle (tabName) {
        this.mainTabs = this.mainTabs.filter(item => item.name !== tabName)
        if (this.mainTabs.length >= 1) {
          // 当前选中tab被删除
          if (tabName === this.mainTabsActiveName) {
            this.$router.push({ name: this.mainTabs[this.mainTabs.length - 1].name }, () => {
              this.mainTabsActiveName = this.$route.name
            })
          }
        } else {
          this.menuActiveName = ''
          this.$router.push({ name: 'home' })
        }
      },
      // tabs, 关闭当前
      tabsCloseCurrentHandle () {
        this.removeTabHandle(this.mainTabsActiveName)
      },
      // tabs, 关闭其它
      tabsCloseOtherHandle () {
        this.mainTabs = this.mainTabs.filter(item => item.name === this.mainTabsActiveName)
      },
      // tabs, 关闭全部
      tabsCloseAllHandle () {
        this.mainTabs = []
        this.menuActiveName = ''
        this.$router.push({ name: 'home' })
      },
      // tabs, 刷新当前
      tabsRefreshCurrentHandle () {
        var tempTabName = this.mainTabsActiveName
        this.removeTabHandle(tempTabName)
        this.$nextTick(() => {
          this.$router.push({ name: tempTabName })
        })
      },

      // 修改密码
      updatePasswordHandle () {
        this.updatePassowrdVisible = true
        this.$nextTick(() => {
          this.$refs.updatePassowrd.init()
        })
      },
      // 退出
      logoutHandle () {
        this.$confirm(`确定进行[退出]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/sys/logout'),
            method: 'post',
            data: this.$http.adornData()
          }).then(({data}) => {
            clearLoginInfo()
            this.$router.push({ name: 'login' })
          })
        }).catch(() => {})
      },

      changeOpenTime(){
        console.log(this.businessTime);
        var startTime = [new Date(this.businessTime[0]).getHours(),new Date(this.businessTime[0]).getMinutes(),new Date(this.businessTime[0]).getSeconds()]
        var endTime = [new Date(this.businessTime[1]).getHours(),new Date(this.businessTime[1]).getMinutes(),new Date(this.businessTime[1]).getSeconds()]

        var openTime = (startTime[0]<10?'0'+startTime[0]:String(startTime[0]))+':'+(startTime[1]<10?'0'+startTime[1]:String(startTime[1]))+':'+(startTime[2]<10?'0'+startTime[2]:String(startTime[2]))+'-' + (endTime[0]<10?'0'+endTime[0]:String(endTime[0]))+':'+(endTime[1]<10?'0'+endTime[1]:String(endTime[1]))+':'+(endTime[2]<10?'0'+endTime[2]:String(endTime[2]))
        console.log(openTime);
        // console.log(dayang);
        // console.log(`${{openTime}}-${{dayang}}`)
        this.$http({
          url: this.$http.adornUrl(`/shop/shopDetail/updateInformation`),
          method: 'put' ,
          params: this.$http.adornParams({
            openTime
          })
        }).then(({ data }) => {
          // this.openTime = openTime
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500,
          })
          this.changeOpenTimeVisible = false
          this.$emit('refresh')
        })
      },

    closeShop(val){
      this.$http({
        url: this.$http.adornUrl("/shop/shopDetail/shopStatus?shopId="+this.shopId+"&shopStatus="+val),
        method: 'put',
      }).then(({data}) => {
        if (data === "success") {
          this.$message({
            message:'操作成功',
            type:'success'
          })
        }
      })
    },

    showstore(){
    },

    switchUser(loginName){
      this.loading = true
      this.$router.replace({name: 'home'})
      this.$http({
        url: this.$http.adornUrl('/sys/logout'),
        method: 'post',
        data: this.$http.adornData()
      }).then(({data}) => {
        clearLoginInfo()
        console.log("request running");
        this.$http({
          url: this.$http.adornUrl('/login?grant_type=admin'),
          method: 'post',
          data: this.$http.adornData({
            'principal': loginName,
            // 'principal': this.dataForm.userName,
            'loginType': 3
          })
        }).then(({ data }) => {
          if (this.savePasswotd) {
            this.$cookie.set('Authorization', 'bearer' + data.access_token,3)
            // this.$cookie.set('userName', this.data.userName,3)
            // this.$cookie.set('password', this.data.password,3)
          }else{
            console.log("request running routerPush");
            this.$cookie.set('Authorization', 'bearer' + data.access_token)
            // this.$router.replace({ name: 'login' })
            // this.$router.replace({ name: 'home' })
            // this.reload()
            // window.reload()
            this.$router.go(0)
            this.loading = false
          }
          // this.$emit('refresh')
        })
      })
    },


  }
}
</script>
<style scoped>

.div-box::-webkit-scrollbar {
    display: none;
  }
.site-content>>>.el-drawer.rtl {
    width: 300px;
    height: calc(100% - 50px);
    top: 50px;
    bottom: 0;
}
.container{
  padding-left: 20px;
}

.site-content>>>.el-collapse-item.is-disabled .el-collapse-item__header{
  color: #303133;
  cursor: pointer;
}
.site-content>>>.el-collapse-item.is-disabled .el-collapse-item__arrow{
  display: none;
}
.site-content>>>.el-collapse-item__header.focusing:focus:not(:hover){
  color: #303133;
}
.site-content>>>.el-date-editor .el-range-separator{
  width: 30px;
}
.site-content>>>.businessTime .el-dialog__body{
  padding-left: 110px;
}
.shopItem >>> .el-collapse-item__header{
  height: 80px;
}
.shopItem >>> .el-collapse-item-title{
  display: flex;
  height: 80px;
  align-items: center;
  justify-content: center;
}
.shopItem >>> .el-collapse-item-title .shopInfo div{
  height: 20px;
  line-height: 20px;
  margin-left: 10px;
  font-size: 15px;
  color: #515151;
}
.shopItem >>> .el-collapse-item-title .shopInfo .createTime{
  font-size: 10px;
  color: #AFAFAF;
}
.menuItem >>> .el-collapse-item__header{
  border: none;
}
</style>
